package com.ironman.compute.consumer;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ironman.common.structure.Bi3Consumer;
import com.ironman.event.properties.SysTrainingProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.dromara.mica.mqtt.codec.MqttQoS;
import org.dromara.mica.mqtt.core.client.MqttClient;
import org.noear.snack.ONode;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Getter
public abstract class BaseConsumer {

    private final AtomicInteger counter = new AtomicInteger(0);

    /**
     * 租户编号
     */
    private final String tenantCode;

    /**
     * 级别ID
     */
    private final String levelId;

    /**
     * 主舵手ID
     */
    private final String mHmId;

    /**
     * mqtt客户端
     */
    private final MqttClient mqttClient;

    public BaseConsumer(SysTrainingProperties sysTrainingProperties, MqttClient mqttClient) {
        this.tenantCode = sysTrainingProperties.getTenantCode();
        this.levelId = sysTrainingProperties.getLevelId();
        this.mHmId = sysTrainingProperties.getMHmId();
        this.mqttClient = mqttClient;
    }

    /**
     * 模板处理
     */
    public void doAccept(String topicType, ONode data, Bi3Consumer<String, String, Boolean> bi3Consumer) {
        // 阈值处理
        if (threshold(data)) {
            // 追加属性
            append(data);
            // 精度处理
            precision(data);
            if (isPublish()) {
                // 发布消息至云端
                publish(topicType, data, bi3Consumer);
            }
        }
    }

    /**
     * 阈值判断
     */
    public boolean threshold(ONode data) {
        return true;
    }

    /**
     * 精度处理
     */
    public void precision(ONode data) {
    }

    /**
     * 追加额外属性
     */
    public void append(ONode data) {

    }

    /**
     * 是否发布消息
     */
    public boolean isPublish() {
        return true;
    }

    /**
     * 发布消息至云端
     */
    private void publish(String topicType, ONode data, Bi3Consumer<String, String, Boolean> bi3Consumer) {
        String topic = StrUtil.format("mobile/up/{}/{}/{}/{}", topicType, tenantCode, levelId, mHmId);
        ONode node = ONode.newObject()
                .set("mHmId", mHmId)
                .set("ts", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN))
                .set("data", data);
        String dataJson = node.toJson();
        boolean published = mqttClient.publish(topic, dataJson.getBytes(StandardCharsets.UTF_8), MqttQoS.QOS1);
        if (Objects.nonNull(bi3Consumer)) {
            bi3Consumer.accept(topic, JSONUtil.toJsonPrettyStr(dataJson), published);
        }
    }
}
